import * as echarts from '../../ec-canvas/echarts';
let clickUrl = ''
let heart = ''
let ec3_1Chart = {}
let ec3_2Chart = {}
Page({
  data: {
    setIntervalDom:"",
    isShow: false,
    navbar: ['总览', '进程', '网络', '系统', '用户'],
    tabbar: ['STATS', 'USED', 'USED(%)', 'AVAIL', 'MOUNT'],
    ramProcessesTabbar: ['PID', 'MEM(%)', 'RSS', 'VSZ'],
    cpuProcessesTabbar: ['PID', 'CPU(%)', 'RSS', 'VSZ'],
    recentLoginsTabbar: ['FROM', 'WHEN'],
    bandwidthTabbar: ['RX', 'TX'],
    AccountsList: ['TYPE', 'HOME'],
    iOStats:['READS','WRITES','IN_PROG','TIME'],
    diskPartitionList: [],
    RamProcessesList: [],
    CpuProcessesList: [],
    BandwidthList: [],
    generalInfoList: {},
    MemoryInfoList: [],
    CPUInfoList: [],
    IOStatsList: [],
    LoggedInAccountsList: [],
    RecentLoginsList: [],
    AccountsList: [],
    UploadTransferRateList: {},
    DownloadTransferRateList: {},
    currentTab: 0,
    ec3_1: {
      onInit: function (canvas, width, height) {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        ec3_1Chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(ec3_1Chart);
      }
    },
    ec3_2: {
      onInit: function (canvas, width, height) {
        //初始化echarts元素，绑定到全局变量，方便更改数据
        ec3_2Chart = echarts.init(canvas, null, {
          width: width,
          height: height
        });
        canvas.setChart(ec3_2Chart);
      }
    },
  },
  // 根据id请求到当前项的url Teb栏循环切换内容
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx
    })
  },
  // 获取列表数据
  getdiskPartitionList() {
    var that = this
    wx.request({
      url: clickUrl + '/server/?module=disk_partitions',
      success: function (res) {
        var diskPartitionList = res.data;
        that.setData({
          diskPartitionList: diskPartitionList
        })
      },
      fail: function (res) {
        var isShow = true
        that.setData({
          isShow: isShow
        })
      },
      complete: function (res) {},
    })
  },
  getRamProcessesList() {
    var that = this
    wx.request({
      url: clickUrl + '/server/?module=ram_intensive_processes',
      success: function (res) {
        var RamProcessesList = res.data;
        that.setData({
          RamProcessesList: RamProcessesList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getCpuProcessesList() {
    var that = this
    wx.request({
      url: clickUrl + '/server/?module=cpu_intensive_processes',
      success: function (res) {
        var CpuProcessesList = res.data;
        that.setData({
          CpuProcessesList: CpuProcessesList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getBandwidthList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=bandwidth",
      success: function (res) {
        var BandwidthList = res.data;
        that.setData({
          BandwidthList: BandwidthList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getUploadTransferRateList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=upload_transfer_rate",
      success: function (res) {
        var dataList = {};
        // 非第一次请求
        if (Object.keys(that.data.UploadTransferRateList).length > 0) {
          dataList = that.data.UploadTransferRateList;
          dataList.x.push([formatTime()])
          dataList['y'][0]['data'].push(res.data.enp0s3);
          dataList['y'][1]['data'].push(res.data.lo);
        } else {
          //1-初始化data数据
          //1.1-初始化X轴
          //1.2-初始化Y轴
          //{'x':[],'y':[]}
          // 时间
          // temp.x.push(); 
          dataList.x = [formatTime()]
          dataList.y = [{
              name: 'enp0s3',
              type: 'line',
              data: [],
            },
            {
              name: 'lo',
              type: 'line',
              data: [],
            }
          ];
          dataList['y'][0]['data'].push(res.data.enp0s3);
          dataList['y'][1]['data'].push(res.data.lo);
        }
        that.setData({
          UploadTransferRateList: dataList,
        })
        initChart3_1(dataList);
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getDownloadTransferRateList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=download_transfer_rate",
      success: function (res) {
        var dataList = {};
        // 非第一次请求
        if (Object.keys(that.data.DownloadTransferRateList).length > 0) {
          dataList = that.data.DownloadTransferRateList;
          dataList.x.push([formatTime()])
          dataList['y'][0]['data'].push(res.data.enp0s3);
          dataList['y'][1]['data'].push(res.data.lo);
        } else { 
          dataList.x = [formatTime()]
          dataList.y = [{
              name: 'enp0s3',
              type: 'line',
              data: [],
            },
            {
              name: 'lo',
              type: 'line',
              data: [],
            }
          ];
          dataList['y'][0]['data'].push(res.data.enp0s3);
          dataList['y'][1]['data'].push(res.data.lo);
        }
        that.setData({
          DownloadTransferRateList: dataList,
        })
        initChart3_2(dataList);
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getGeneralInfoList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=general_info",
      success: function (res) {
        var generalInfoList = res.data;
        that.setData({
          generalInfoList: generalInfoList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getMemoryInfoList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=memory_info",
      success: function (res) {
        var MemoryInfoList = res.data;
        that.setData({
          MemoryInfoList: MemoryInfoList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getCPUInfoList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=cpu_info",
      success: function (res) {
        var CPUInfoList = res.data;
        that.setData({
          CPUInfoList: CPUInfoList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getIOStatsList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=io_stats",
      success: function (res) {
        var IOStatsList = res.data;
        that.setData({
          IOStatsList: IOStatsList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getLoggedInAccountsList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=logged_in_users",
      success: function (res) {
        var LoggedInAccountsList = res.data;
        that.setData({
          LoggedInAccountsList: LoggedInAccountsList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getRecentLoginsList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=recent_account_logins",
      success: function (res) {
        var RecentLoginsList = res.data;
        that.setData({
          RecentLoginsList: RecentLoginsList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  getAccountsList() {
    var that = this
    wx.request({
      url: clickUrl + "/server/?module=user_accounts",
      success: function (res) {
        var AccountsList = res.data;
        that.setData({
          AccountsList: AccountsList
        })
      },
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  // 微信小程序设置一个定时器
  startSetInter: function () {
    var that = this;
    // 将计时器赋值给setInter
    this.data.setIntervalDom=setInterval(
      function () {
        that.gethanshulist()
      },heart*1000);
      // that.setData({
      //   setIntervalDom: setIntervalDom
      // })  
  },
  // 集中获取数据
  gethanshulist() {
    this.getdiskPartitionList()
    this.getRamProcessesList()
    this.getCpuProcessesList()
    this.getBandwidthList()
    this.getGeneralInfoList()
    this.getMemoryInfoList()
    this.getCPUInfoList()
    this.getIOStatsList()
    this.getLoggedInAccountsList()
    this.getRecentLoginsList()
    this.getAccountsList()
    this.getUploadTransferRateList()
    this.getDownloadTransferRateList()
  },
  onLoad: function (options) {
    clickUrl = options.id,
    heart = options.heart
    this.gethanshulist()
    this.startSetInter()
  },
  onHide: function () {
    // 页面隐藏    
    //关闭定时器    
    clearInterval(this.data.setIntervalDom);
    },
    
    onUnload: function () {    
    // 页面关闭    
    //关闭定时器    
    clearInterval(this.data.setIntervalDom);    
    },
})
//这是第三（一）张图表
function initChart3_1(tempData1 = {}) {
  var option3_1 = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tempData1.x
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: tempData1.y
  };
  ec3_1Chart.setOption(option3_1);
}
//这是第三（二）张图表
function initChart3_2(tempData2 = {}) {
  var option3_2 = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {},
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: tempData2.x
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} '
      }
    },
    series: tempData2.y
  };
  ec3_2Chart.setOption(option3_2);
}
// 时间的处理
function formatTime() {
  var date = new Date();
  // const year = date.getFullYear()
  // const month = date.getMonth() + 1
  // const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return hour + ':' + minute + ':' + second
}